import {
  ADD_ITEM,
  PUSH_END,
  PUSH_PANDING,
  DELETE_ITEM,
  DELE_ITEM_END
} from "../actionType";
const initState = {
  // 正在进行中
  panding: [
    // { id: 1, checked: false, text: "今天吃十个包子" },
    // { id: 2, checked: false, text: "今天吃包子" }
  ],
  // { id: 1, checked: false, text: "今天吃十个包子" }
  // 完成
  end: []
};
export default (state = initState, action) => {
  let newState = JSON.parse(JSON.stringify(state));
  switch (action.type) {
    // 添加一条
    case ADD_ITEM:
      let panding = newState.panding;
      let id = 1;
      // 简单判断
      if (panding.length) {
        id = panding[panding.length - 1].id + 1;
      }
      panding.push({
        id: id,
        checked: false,
        text: action.value
      });
      // 重新赋值
      newState.panding = panding;
      // 返回新的状态
      return newState;
    // push到已完成
    case PUSH_END:
      // 通过id找下标
      const aid = action.id;
      // 通过下标删除并返回被删除的数据
      const itemIndex = newState.panding.findIndex(item => item.id === aid);

      const itemData = newState.panding.splice(itemIndex, 1);
      // 把被删除掉的数据插入到end中
      itemData[0].checked = true;
      newState.end.push(itemData[0]);
      return newState;
    // 从已完成push到正在进行
    case PUSH_PANDING:
      // 通过id找下标
      const bid = action.id;
      // 不理解
      const deleIndex = newState.end.findIndex(item => item.id === bid);
      const deleItem = newState.end.splice(deleIndex, 1);
      deleItem[0].checked = false;
      newState.panding.push(deleItem[0]);
      return newState;
    // 从正在完成中删除一条
    case DELETE_ITEM:
      const cid = action.id;
      // 选中点击时的元素
      const chlickItem = newState.panding.findIndex(item => item.id === cid);
      // 从panding数组中删除
      newState.panding.splice(chlickItem, 1);
      return newState;
    case DELE_ITEM_END:
      const did = action.id;
      const chlickItemEnd = newState.end.findIndex(item => item.id === did);
      // 从panding数组中删除
      newState.end.splice(chlickItemEnd, 1);
      return newState;
    default:
      return state;
  }
};
